package com.campus.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.campus.domain.dto.LoginFormDTO;
import com.campus.domain.dto.RegisterFormDTO;
import com.campus.domain.dto.UpdateUserDTO;
import com.campus.domain.dto.UserDTO;
import com.campus.domain.entity.*;
import com.campus.domain.vo.*;
import com.campus.mapper.*;
import com.campus.service.IUserService;
import com.campus.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ActivityEnrollmentMapper activityEnrollmentMapper;
    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private ActivityImageMapper activityImageMapper;
    @Resource
    private LostItemClaimMapper lostItemClaimMapper;
    @Resource
    private LostItemMapper lostItemMapper;
    @Resource
    private LostItemImageMapper lostItemImageMapper;
    @Resource
    private UserPermissionMapper userPermissionMapper;

    /**
     * 用户注册
     */
    @Override
    public RegisterVO register(RegisterFormDTO registerFormDTO) {
        //验证两次传来的密码是否一致
        if(!registerFormDTO.getPassword().equals(registerFormDTO.getConfirmPassword())){
            throw new RuntimeException("两次输入的密码不一致");
        }
        //验证用户名是否已被被人占用
        Long count = userMapper.count(registerFormDTO.getUsername());
        if(count > 0){
            throw new RuntimeException("用户名已被占用");
        }
        //对密码进行加密然后保存
        String encode = passwordEncoder.encode(registerFormDTO.getPassword());
        User user = User.builder()
                .userName(registerFormDTO.getUsername())
                .password(encode)
                .avatar("https://tlias-0626.oss-cn-hangzhou.aliyuncs.com/2025/06/86dff275-7fc9-45a5-b31a-2b97b96ddb39.png")
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .userType(1)
                .build();
        //保存用户
        userMapper.save(user);
        return new RegisterVO(user.getUserName(), user.getId());
    }
    /**
     * 用户登录
     */
    @Override
    public String login(LoginFormDTO loginFormDTO) {
        //AuthenticationManager authenticate用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginFormDTO.getUsername(), loginFormDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过，生成jwt token
        UserDTO userDTO = (UserDTO)authenticate.getPrincipal();
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userDTO.getId());
        map.put("userName",userDTO.getUsername());
        map.put("avatar",userDTO.getAvatar());
        List<String> permissions = userDTO.getPermissions();
        String jsonString = JSON.toJSONString(permissions);
        map.put("permissions",jsonString);
        return JwtUtil.createJwt(map);
    }
    /**
     * 获取用户信息
     */
    @Override
    public UserInfoVO getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO)authentication.getPrincipal();
        //获取用户菜单权限
        List<String> routes = userPermissionMapper.getRoutes(userDTO.getId());
        UserInfoVO userInfoVO = new UserInfoVO(userDTO.getUsername(), userDTO.getAvatar(), userDTO.getPermissions(),routes);
        userInfoVO.setUserId(userDTO.getId());
        return userInfoVO;
    }
    /**
     * 根据用户名查询用户信息
     */
    @Override
    public User selectByUserName(String userName) {
        return userMapper.selectByUserName(userName);
    }
    /**
     * 查询用户按钮权限
     */
    @Override
    public List<String> getButtonPermission(Long id) {
        return userMapper.getButtonPermission(id);
    }
    
    /**
     * 获取用户详细信息
     */
    @Override
    public UserDetailVO getUserDetail() {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        
        // 查询用户完整信息
        User user = userMapper.findById(userDTO.getId());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 转换为VO
        UserDetailVO userDetailVO = new UserDetailVO();
        userDetailVO.setId(user.getId());
        userDetailVO.setUsername(user.getUserName());
        userDetailVO.setAvatar(user.getAvatar());
        userDetailVO.setEmail(user.getEmail());
        userDetailVO.setPhone(user.getPhone());
        
        return userDetailVO;
    }
    
    /**
     * 更新用户信息
     */
    @Override
    public void updateUserInfo(UpdateUserDTO updateUserDTO) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        
        // 构建User对象
        User user = new User();
        user.setId(userDTO.getId());
        user.setEmail(updateUserDTO.getEmail());
        user.setPhone(updateUserDTO.getPhone());
        user.setUpdateTime(LocalDateTime.now());
        
        // 更新数据库
        userMapper.updateUserInfo(user);
    }
    
    /**
     * 获取用户报名的活动列表
     */
    @Override
    public List<UserEnrollmentVO> getUserEnrollments() {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        
        // 查询用户所有报名记录
        List<ActivityEnrollment> enrollments = activityEnrollmentMapper.selectByUserId(userDTO.getId());
        
        // 转换为VO
        return enrollments.stream().map(enrollment -> {
            UserEnrollmentVO vo = new UserEnrollmentVO();
            vo.setEnrollmentId(enrollment.getId());
            vo.setActivityId(enrollment.getActivityId());
            vo.setEnrollStatus(enrollment.getStatus());
            vo.setEnrollTime(enrollment.getEnrollTime());
            
            // 查询活动详情
            Activity activity = activityMapper.selectById(enrollment.getActivityId());
            if (activity != null) {
                vo.setActivityTitle(activity.getTitle());
                vo.setActivityDescription(activity.getDescription());
                vo.setActivityStartTime(activity.getStartTime());
                vo.setActivityEndTime(activity.getEndTime());
                vo.setActivityLocation(activity.getLocation());
                
                // 动态计算活动状态
                LocalDateTime now = LocalDateTime.now();
                if (now.isBefore(activity.getStartTime())) {
                    vo.setActivityStatus(0); // 未开始
                } else if (now.isAfter(activity.getEndTime())) {
                    vo.setActivityStatus(2); // 已结束
                } else {
                    vo.setActivityStatus(1); // 进行中
                }
                
                // 查询活动图片
                List<ActivityImage> images = activityImageMapper.selectByActivityId(activity.getId());
                vo.setActivityImages(images.stream()
                        .map(ActivityImage::getImageUrl)
                        .collect(Collectors.toList()));
            }
            
            return vo;
        }).collect(Collectors.toList());
    }
    
    /**
     * 获取用户申领的失物列表
     */
    @Override
    public List<UserClaimVO> getUserClaims() {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        
        // 查询用户所有申领记录
        List<LostItemClaim> claims = lostItemClaimMapper.selectByUserId(userDTO.getId());
        
        // 转换为VO
        return claims.stream().map(claim -> {
            UserClaimVO vo = new UserClaimVO();
            vo.setClaimId(claim.getId());
            vo.setItemId(claim.getItemId());
            vo.setClaimStatus(claim.getStatus());
            vo.setReason(claim.getReason());
            vo.setContactInfo(claim.getContactInfo());
            vo.setAuditReason(claim.getAuditReason());
            vo.setClaimTime(claim.getCreateTime());
            vo.setAuditTime(claim.getAuditTime());
            
            // 查询失物详情
            LostItem item = lostItemMapper.selectById(claim.getItemId());
            if (item != null) {
                vo.setItemTitle(item.getTitle());
                vo.setItemCategory(item.getCategory());
                vo.setItemLocation(item.getLocation());
                vo.setItemFoundTime(item.getFoundTime());
                vo.setItemStatus(item.getStatus());
                
                // 查询失物图片
                List<LostItemImage> images = lostItemImageMapper.selectByItemId(item.getId());
                vo.setItemImages(images.stream()
                        .map(LostItemImage::getImageUrl)
                        .collect(Collectors.toList()));
            }
            
            return vo;
        }).collect(Collectors.toList());
    }
}
